package com.demo.systemmonitor;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.demo.systemmonitor.data.CpuData;
import com.demo.systemmonitor.utils.CpuUtils;
import com.demo.systemmonitor.utils.MemoryUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import java.util.Timer;
import java.util.TimerTask;

public class SystemDataStorageService extends Service {
    private static final String TAG = "SystemDataStorageService";
    private static final int SAVE_INTERVAL_MS = 5000; // 5秒保存一次
    private static final long MAX_STORAGE_DURATION_MS = 240 * 60 * 60 * 1000L; // 240小时
    
    private Timer timer;
    private Handler handler;
    private File dataDirectory;
    private SimpleDateFormat dateFormat;
    private SimpleDateFormat timeFormat;
    
    // 当前数据文件（合并CPU和内存数据）
    private File currentDataFile;
    private long currentFileStartTime;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service created");
        
        handler = new Handler(Looper.getMainLooper());
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        
        // 创建数据存储目录
        dataDirectory = new File(getExternalFilesDir(null), "system_data");
        if (!dataDirectory.exists()) {
            dataDirectory.mkdirs();
        }
        
        // 清理旧数据文件
        cleanupOldDataFiles();
        
        // 创建当前数据文件
        createCurrentDataFile();
        
        // 启动定时保存
        startDataCollection();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service started");
        return START_STICKY; // 确保服务被杀死后能重启
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service destroyed");
        stopDataCollection();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    private void startDataCollection() {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                collectAndSaveData();
            }
        }, 2000, SAVE_INTERVAL_MS);
    }
    
    private void stopDataCollection() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
    
    private void collectAndSaveData() {
        try {
            // 收集CPU数据
            CpuData cpuData = CpuUtils.getCpuData();
            // 收集内存数据
            MemoryUtils.MemoryData memoryData = MemoryUtils.getMemoryData();
            
            if (cpuData != null && memoryData != null) {
                saveCombinedData(cpuData, memoryData);
            }
            
            // 检查是否需要创建新文件（每天创建新文件）
            checkAndCreateNewFile();
            
  
            
        } catch (Exception e) {
            Log.e(TAG, "Error collecting data", e);
        }
    }
    
    private void saveCombinedData(CpuData cpuData, MemoryUtils.MemoryData memoryData) {
        try {
            if (currentDataFile != null) {
                String timestamp = timeFormat.format(new Date());
                String dataLine = String.format(Locale.getDefault(), 
                    "%s,%.2f,%.2f,%s,%d,%d,%.1f,%.2f,%d,%d,%d,%d\n",
                    timestamp,                    // 时间
                    cpuData.getUsage(),          // CPU使用率
                    cpuData.getFrequency(),      // CPU频率
                    cpuData.getSpeed(),          // CPU速度
                    cpuData.getProcesses(),      // 进程数
                    cpuData.getThreads(),        // 线程数
                    cpuData.getTemperatureC() != null ? cpuData.getTemperatureC() : 0.0f, // CPU温度
                    memoryData.getUsagePercent(), // 内存使用率
                    memoryData.getTotalMemory(),  // 总内存
                    memoryData.getUsedMemory(),   // 已用内存
                    memoryData.getFreeMemory(),   // 空闲内存
                    memoryData.getAvailableMemory() // 可用内存
                );
                
                appendToFile(currentDataFile, dataLine);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error saving combined data", e);
        }
    }
    
    private void appendToFile(File file, String data) {
        try (FileWriter writer = new FileWriter(file, true)) {
            writer.append(data);
            writer.flush();
        } catch (IOException e) {
            Log.e(TAG, "Error writing to file: " + file.getName(), e);
        }
    }
    
    private void createCurrentDataFile() {
        String dateStr = dateFormat.format(new Date());
        currentFileStartTime = System.currentTimeMillis();
        
        // 创建合并的数据文件
        currentDataFile = new File(dataDirectory, "system_data_" + dateStr + ".csv");
        
        // 写入CSV头部
        writeCsvHeader(currentDataFile, 
            "时间,CPU使用率(%),CPU频率(MHz),CPU速度,进程数,线程数,CPU温度(°C)," +
            "内存使用率(%),总内存(MB),已用内存(MB),空闲内存(MB),可用内存(MB)");
    }
    
    private void writeCsvHeader(File file, String header) {
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(header + "\n");
            writer.flush();
        } catch (IOException e) {
            Log.e(TAG, "Error writing CSV header to: " + file.getName(), e);
        }
    }
    
    private void checkAndCreateNewFile() {
        String currentDateStr = dateFormat.format(new Date());
        String fileDateStr = extractDateFromCurrentFileName();
        
        Log.d(TAG, "Checking file creation: currentDate=" + currentDateStr + ", fileDate=" + fileDateStr);
        
        // 如果无法提取文件日期，或者日期不同，创建新文件
        if (fileDateStr == null || !currentDateStr.equals(fileDateStr)) {
            Log.d(TAG, "Creating new file: fileDate=" + fileDateStr + ", currentDate=" + currentDateStr);
            createCurrentDataFile();
        } else {
            Log.d(TAG, "Same date, no need to create new file");
        }
    }
    
    // 从当前文件名提取日期
    private String extractDateFromCurrentFileName() {
        if (currentDataFile != null && currentDataFile.exists()) {
            String fileName = currentDataFile.getName();
            // 处理 system_data_2024-01-15.csv 格式
            if (fileName.startsWith("system_data_") && fileName.endsWith(".csv")) {
                String dateStr = fileName.substring(12, fileName.length() - 4);
                Log.d(TAG, "Extracted date from filename: " + dateStr);
                return dateStr;
            }
        }
        Log.w(TAG, "Cannot extract date from filename, current file: " + 
            (currentDataFile != null ? currentDataFile.getName() : "null"));
        return null; // 返回null而不是当前日期
    }
    
    private void cleanupOldDataFiles() {
        File[] files = dataDirectory.listFiles();
        if (files != null) {
            long cutoffTime = System.currentTimeMillis() - MAX_STORAGE_DURATION_MS;
            int deletedCount = 0;
            
            for (File file : files) {
                // 从文件名提取日期来判断，而不是文件修改时间
                String fileName = file.getName();
                if (fileName.startsWith("system_data_") && fileName.endsWith(".csv")) {
                    String dateStr = fileName.substring(12, fileName.length() - 4);
                    try {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        Date fileDate = dateFormat.parse(dateStr);
                        
                        // 如果文件日期超过240小时前，删除文件
                        if (fileDate.getTime() < cutoffTime) {
                            if (file.delete()) {
                                deletedCount++;
                                Log.d(TAG, "Deleted old data file: " + file.getName());
                            }
                        }
                    } catch (ParseException e) {
                        Log.w(TAG, "Error parsing date from filename: " + fileName, e);
                    }
                }
            }
            
            Log.d(TAG, "Cleaned up " + deletedCount + " old data files");
        }
    }
    

    
    /**
     * 获取所有数据文件列表
     */
    public static File[] getDataFiles(File dataDirectory) {
        if (dataDirectory != null && dataDirectory.exists()) {
            return dataDirectory.listFiles((dir, name) -> name.startsWith("system_data_"));
        }
        return new File[0];
    }
    
    /**
     * 获取数据存储目录
     */
    public static File getDataDirectory(android.content.Context context) {
        return new File(context.getExternalFilesDir(null), "system_data");
    }
}
